import Taro from '@tarojs/taro'
import qs from 'qs';
import { wxLogin } from './wx.js';
import config from './config';
import api from './api';


const urlCache = {}; // 请求的Api缓存
let clearTimerId = 0;
const limitTime = 1 * 10 * 1000;
const checkUrlRepeat = ({ url, method }) => {
  const currentDatetime = new Date().getTime();
  // 非POST请求放过  登录接口放过
  if (method !== 'POST' || url.includes('user/login')) {
    return false;
  }
  // 防止重复请求
  if (!urlCache[url] || (urlCache[url] && currentDatetime - urlCache[url] > limitTime)) {
    urlCache[url] = new Date().getTime();
    return false;
  }
  // 清理垃圾数据
  clearTimeout(clearTimerId);
  clearTimerId = setTimeout(() => {
    console.log(5,{...urlCache});
    const dateTime = new Date().getTime();
    const keys = Object.keys(urlCache);
    for (const item of keys) {
      if (
        urlCache[item] &&
        urlCache[url] &&
        dateTime - urlCache[url] > limitTime
      ) {
        urlCache[item] = null;
      }
    }
  }, limitTime);
  return true;
};

var clearCache = function(url) {
  urlCache[url] = null;
}

function request({ method = 'GET', tartget, header = {}, data = {} }) {
  const url = api[tartget];
  if (!url || checkUrlRepeat({ url, method })) {
    return new Promise((resolve)=>{
      resolve({});
    });
  }

  let urlTemp = config.apiPrefix + url;
  if (method === 'GET') {
    urlTemp = urlTemp + qs.stringify(data, {
      addQueryPrefix: true,
      allowDots: true,
    });
  }
  header["Authorization"] = Taro.getStorageSync('token') || '';
  header['Client'] = config.client;
  return new Promise((resolve, reject) => {
    Taro.request({
      method,
      url: urlTemp,
      header,
      data: method === 'GET' ? null : data,
      success(res) {
        // 请求成功
        // if (method != 'GET') {
        //   urlCache[url] = null;
        // }
        if (res.statusCode === 200) {
          if (res.data.resultCode === '00999') {
            console.log(1);
            Taro.setStorageSync('token', '');
            wxLogin();
            return;
          }
          if (res.data && res.data.success !== 1 && res.data.resultCode !== '00999') {
            Taro.showToast({
              title: res.data.message || '操作失败',
              icon: 'none',
            });
          }
          resolve(res.data);
          return;
        }

        // 未认证
        else if (res.statusCode === 401) {
          /* 可做一些错误提示，或者直接跳转至登录页面等 */
          reject(res)
        }
        else if (res.statusCode == 400) {
          /* 可做一些错误提示*/
          reject(res)
        }
        else if (res.statuCode === 403) {
          /* 无权限错误提示*/
          reject(res)
        }
        // ...其他状态码处理
      },
      fail(err) {
        /* 可做一些全局错误提示，如网络错误等 */
        reject(err)
      },
      complete() {
        setTimeout(function() {
          if (method != 'GET') {
            clearCache(url);
          }
        }, 5000);
      }
    })
  })
}

export default request;
